package com.justgame.project.base.interceptor;

import com.justgame.project.base.annotation.UploadApi;

import com.justgame.project.cloud.common.constant.Result;
import com.justgame.project.cloud.common.util.AppContextUtils;
import com.justgame.project.cloud.common.util.FileUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;

/**
 * OSS保护拦截器 - Part of Response
 */
@Slf4j
@AllArgsConstructor
@ControllerAdvice("com.justgame.project.module.controller")
public class ProtectOssResponseInterceptor implements ResponseBodyAdvice<Result<?>> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        Method method = returnType.getMethod();
        if (method == null) return false;
        /* 不是上传接口 */
        return method.getAnnotation(UploadApi.class) == null;
    }


    @Override
    public Result<?> beforeBodyWrite(Result<?> body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body != null && body.getCode() != null && body.getCode() == 200 && request.getMethod() != HttpMethod.GET) {
            /* 异步非阻塞执行 */
            AppContextUtils.getBean(FileUtils.class).asyncClearFileTask(request);
        }
        return body;
    }
}
